
package com.meis.widget.utils;

import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.global.configuration.DeviceCapability;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;

/**
 * 尺寸转换工具类
 */
public class DensityUtil {

    /**
     * dp to px
     *
     * @param context 上下文
     * @param dpValue dp数值
     * @return dp to px
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes().densityPixels;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 获取屏幕高度
     *
     * @param context Context
     * @return int ScreenHeight
     */
    public static int getScreenHeight(Context context) {
        DeviceCapability deviceCapability = context.getResourceManager().getDeviceCapability();
        return deviceCapability.height;
    }

    /**
     * 获取像素尺寸
     *
     * @param context Context
     * @param res     资源Id
     * @return int PixelSize
     */
    public static int getDimensionPixelSize(Context context, int res) {
        int result = 0;
        try {
            result = (int) context.getResourceManager().getElement(res).getFloat();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        return result;
    }
}